package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author buyandalai
 */
public class server extends Thread  {
    public static final int DEFAULT_PORT = 6666;
    ServerSocket serverSocket;
    Socket socket;
    window win;
    public server(window win){
        this.win = win;
    }

    @Override
    public void run()
    {
        int port = win.getPort();
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("created socket");
            while (true) {
                socket = serverSocket.accept();
                win.client_connected(socket.getInetAddress().getHostAddress());
                chatHandler handler = new chatHandler(socket);
                handler.start();
            }
        } catch (IOException ex) {
            javax.swing.JOptionPane.showMessageDialog(win.getRootPane(), "This port is already taken by another application! Please enter a different port number!",
                                         "Error!",
                                         javax.swing.JOptionPane.ERROR_MESSAGE);
            win.stopServer();
        }finally{
            try{
                serverSocket.close();
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }

    }

    public void close()
    {
        try {
            serverSocket.close();
        } catch (IOException ex) {
            Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
